<template>
  <basic-container>
    <el-dialog :append-to-body="true" :before-close="cancelDialog" :close-on-click-modal="false" :modal="false"
               :title="'整改报告'" :visible.sync="dialog" custom-class="ledger" fullscreen top="5vh"
               width="1200px">
      <div class="colums">
        <div class="colums_left">
          <div class="colums_left_middle">
            <div class="middleForm ledger">
              <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
                <div class="title">项目信息</div>
                <el-row>
                <el-col :span="8">
                  <el-form-item label="项目名称:" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="请输入项目名称"></el-input>
                  </el-form-item>
                </el-col>
                  <el-col :span="8">
                  <el-form-item label="整改责任单位:" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
                  <el-col :span="8">
                  <el-form-item label="审计组组长/主审:" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </el-col>
                </el-row>
                <div class="title">整改情况</div>
                <el-row>
                  <el-col>
                    <el-button icon="el-icon-plus" size="small" type="primary" @click="onAddItem('')">新建</el-button>
                     <el-button icon="el-icon-document-copy" @click="addSelectedRow">复制</el-button>
                    <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                    <el-button icon="el-icon-delete-solid" @click="clearTableData">删除全部</el-button>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col>
                    <el-table
                      ref="table"
                      :data="tableData"
                      :model="tableData"
                      v-loading="loading"
                      style="width: 100%"
                      max-height="450"
                      highlight-current-row
                      @selection-change="updateSelectedRows"
                      @current-change="handleCurrentChange"
                    >
                      <el-table-column type="selection" width="55" align="center"></el-table-column>
                      <el-table-column label="序号" width="100">
                        <template #default="{ $index }">
                          <span>{{ $index + 1 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="问题标题" width="300">
                        <template #default="{ row }">
                          <el-input v-model="row.problemTitle" type="textarea" :autosize="{ minRows: 2}"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="整改期限" width="300">
                        <template #default="{ row }">
                          <div class="block">
                            <el-date-picker
                              v-model="row.deadline"
                              type="date"
                              placeholder="选择日期">
                            </el-date-picker>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column label="整改措施">
                        <template #default="{ row, $index  }">
                          <el-input v-model="row.rectificationMeasures" type="textarea" :autosize="{ minRows: 2}" placeholder="输入整改措施" @blur="handleMouseLeave($index)"></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column label="完成情况" width="120">
                        <template #default="{ row }">
                          <el-select v-model="row.rectifyStatus" placeholder="请选择">
                            <el-option v-for="item in dict.type.ectification_situation" :key="item.value" :label="item.label" :value="parseInt(item.value)"></el-option>
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column label="是否销号" width="120">
                        <template #default="{ row }">
                          <el-select v-model="row.isCancellation" placeholder="请选择">
                            <el-option :label=" '是' " :value="1"></el-option>
                            <el-option :label=" '否' " :value="0"></el-option>
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column label="佐证资料" width="280">
                        <template #default="{ row, $index }">
                          <el-upload
                            class="upload-demo"
                            ref="upload"
                            action="/admin/sys-file/upload"
                            :headers="{Authorization}"
                            :on-success="(e) => handleSuccess(e, $index)"
                            :on-preview="handlePreview"
                            :on-remove="(file, fileList) => handleRemove(file, fileList, $index)"
                            :show-file-list="true"
                            :file-list="row.fileList">
                            <i class="el-icon-paperclip" style="color: #409EFF;"></i>
                          </el-upload>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
                <div class="title">整改报告</div>
                <el-row>
                  <el-col>
                    <el-form-item label="整改报告:">
                      <web-document :form-data="form" :readWord="'edit'" :pageType="'rectifyReport'" @createWordFile="wordFileHandle" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
                <el-button v-if="!isView/** && form.status !== 1 && form.status !== 3 */" icon="el-icon-check" size="small" type="primary" @click="submit" :loading="loading">保存</el-button>
                <el-button v-if="!isView && form.status !== 1 && form.status !== 3" icon="el-icon-check" size="small" type="primary" @click="saveSubmit" :loading="loading">提交</el-button>
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <ChoseProject :projectDialog="projectDialog" @cancelDialog="closeProjectDialog" @setValue="projectDataHandle" ref="ChoseProject"/>

  </basic-container>
</template>


<script>
import ChoseProject from "@/components/audited/ChoseProject.vue";
import {submit,getDiscover,getRectifyReport,saveSubmit} from "@/api/adis/track/rectifyReprot";
import {getSysFile} from "@/api/admin/file"
import WebDocument from "@/components/form/webDocument.vue";

export default {
  components: {WebDocument, ChoseProject},
  // props: {
  //   dialog: Boolean,
  // },
  dictTypes: ['audit_type_1_sub'],
  data(){
    return{
      isHidden:true,
      dialog: false,
      loading: false,
      tableData:[{
        templateId : 1
      }],
      selectedRows: [],
      selectedRow: {},
      form:{
        employmentDates:[]
      },
      projectDialog:false,
      projectForm:{},
      isView:false,
      formDisplay:false,
      templateForm: [],
      Authorization: '',
      attachment:{},
    }
  },
  watch: {
    // 检测资料清单，如果被全数删除，立即补充一条空的清单
    tableData(newVal){
      if ((!newVal || newVal.length <= 1) && this.tableData.length <= 0){
        this.onAddItem()
      }
    },
  },
  created() {
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    onAddItem(val) {
      // 在这里添加添加新项目的逻辑
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        attachmentType: val.attachmentType || '',
        templateId: this.tableData.length + 1,
        projectId: val.projectId || '',
        problemTitle: val.problemTitle || '',
        problemDesc: val.problemDesc || '',
        rectificationMeasures: val.rectificationMeasures || '',
      })
    },
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        this.onAddItem(this.selectedRow)
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        const index = this.tableData.indexOf(this.selectedRow);
        if (index !== -1) {
          this.tableData.splice(index, 1);
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
    },
    // -- 资料上传
    handleRemove(file, fileList, i) {
      this.tableData[i].fileList.forEach((item, v) => {
        if (file.url === item.url) this.tableData[i].fileList.splice(v, 1)
      })
    },
    handlePreview (file) {
      // console.log(file.url);
      const a = document.createElement('a');
      let url = file.url ? file.url : file.response.data.url;
     // let fileName = '你想要的文件名.docx'; // 这里设置你想要的文件名，包括扩展名
      a.setAttribute('download', file.name);
      a.setAttribute('href', url);
      a.click();
      // this.attachment.filePath = file.url ? file.url : file.response.data.url;
      // this.attachment.fileName = file.name;
      // let encodedPath = encodeURIComponent(this.attachment.filePath);
      // let encodedName = encodeURIComponent(this.attachment.fileName);
      // getSysFile(encodedPath,encodedName);
      // window.open(file.url ? file.url : file.response.data.url)
    },
    handleMouseLeave(index){
      console.log("123456")
      if (this.tableData.length-1 === index){
        console.log("321654")
        this.form.rectifyReportProblems = []
        this.tableData.forEach((item, i) => {
          this.form.rectifyReportProblems.push(item)
        })
        console.log(this.form)
      }
    },
    handleSuccess(e, v) {
      if (!this.tableData[v].fileList) {
        this.tableData[v].fileList = [{url: e.data.url, name: e.data.fileName}]
      } else {
        this.tableData[v].fileList.push({url: e.data.url, name: e.data.fileName})
      }
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },
    handleCurrentChange(selection){
      this.selectedRow = selection;
    },

    showProjectDialog() {
      this.projectDialog = true
      this.$refs.ChoseProject.initParams({
        hasRectify: true,//是否已发起整改通知书
        hasRectifyReport: false ,// 是否已生成整改报告
        isEngineering: false,//是否工程审计
        isTermination: false
      });
    },
    closeProjectDialog() {
      this.projectDialog = false
    },
    projectDataHandle(row){
      this.projectDialog = false
      this.projectForm = row;
      let newForm = this.form;
      newForm.projectId = this.projectForm.projectId;
      newForm.projectName = this.projectForm.projectName;
      this.form = newForm;
      getDiscover(this.projectForm.projectId).then((res)=>{
        this.tableData = res.data.data.projectReportProblems;
        this.form.number = "〔"+res.data.data.reportYear+"〕"+res.data.data.reportCode;
      })
    },
    init(row,isHidden){
      this.isHidden = isHidden;
      if (row.rectifyId){
        getRectifyReport(row.rectifyId).then((res)=>{
          this.$set(this, "form", res.data.data);
          this.form.number = "〔"+this.form.reportYear+"〕"+this.form.reportCode;
          this.dialog = true;

          // 打开页面后再加载tableData,避免出现文本框渲染错误的情况
          if (this.form.rectifyReportProblems && this.form.rectifyReportProblems.length > 0){
            this.loading = true
            setTimeout(() => {
              this.tableData = this.form.rectifyReportProblems || []
              this.tableData.forEach(item => {
                item.fileList = []
                item.attachments.forEach(col => {
                  item.fileList.push({name: col.fileName, url: col.fileUrl})
                })
              })
              this.loading = false
            }, 500)
          }
        })
      }else if(row.projectId){
        getDiscover(row.projectId).then((res)=>{
          this.form.projectName = res.data.data.projectName;
          this.form.projectId = res.data.data.projectId;
          this.form.rectifyId = res.data.data.rectifyId;
          this.tableData = res.data.data.projectReportProblems?res.data.data.projectReportProblems:res.data.data.rectifyReportProblems;
          this.form.number = "〔"+res.data.data.reportYear+"〕"+res.data.data.reportCode;
          console.log(res);
          this.dialog = true;
        })
      } else {
        this.dialog = true;
      }
    },
    cancelDialog(){
      this.dialog = false;
      this.$emit('cancelDialog', {})
      this.$refs['dataForm'].resetFields()
    },
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(item.rectificationMeasures === ''){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行整改措施不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.rectifyReportProblems = []
          this.tableData.forEach((item, i) => {
            item.attachments = []
            item.projectId = this.form.projectId
            if (item.fileList) {
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.rectifyReportProblems.push(item)
          })
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    saveSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(item.rectificationMeasures === ''){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行整改措施不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.rectifyReportProblems = []
          this.tableData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList) {
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.rectifyReportProblems.push(item)
          })
          this.loading = true;
          saveSubmit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },
    wordFileHandle(e) {
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "rectifyId", e.id);
    }
  }
}
</script>
<style scoped>
.custom-textarea /deep/ textarea {
  font-size: 15px; /* 设置字体大小 */
  color: #333; /* 设置字体颜色 */
}
</style>
